package com.nulldev.util.scripting.ScriptAPI.plusExt.rhino;

import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import com.nulldev.util.JVM.reflections.Reflections;
import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.internal.backport.concurrency9.Lists;
import com.nulldev.util.manage.Unimplemented;
import com.nulldev.util.scripting.ScriptAPI.nScripting;

public class RhinoJSEFactory implements ScriptEngineFactory {

	private static final List<String> names = immutableList("rhino", "Rhino", "Mozilla Rhino", "js", "JS", "JavaScript", "javascript", "ECMAScript",
			"ecmascript");
	private static final List<String> mimeTypes = immutableList("application/javascript", "application/ecmascript", "text/javascript", "text/ecmascript");
	private static final List<String> extensions = immutableList("js");

	public RhinoJSEFactory() {
		if (!Reflections.is("org.mozilla.javascript.Context"))
			throw new RuntimeException("RhinoJS not found!");
	}

	@Override
	public String getEngineName() {
		return "Rhino";
	}

	@Override
	public String getEngineVersion() {
		return "1.0.1_1.7";
	}

	@Override
	public List<String> getExtensions() {
		return extensions;
	}

	@Override
	public List<String> getMimeTypes() {
		return mimeTypes;
	}

	@Override
	public List<String> getNames() {
		return names;
	}

	@Override
	public String getLanguageName() {
		return "javascript";
	}

	@Override
	public String getLanguageVersion() {
		return "6.0.0";
	}

	@Override
	public Object getParameter(final String key) {
		if (key.equals("javax.script.engine_version")) {
			return this.getEngineVersion();
		} else if (key.equals("javax.script.engine")) {
			return this.getEngineName();
		} else if (key.equals("javax.script.language_version")) {
			return this.getLanguageVersion();
		} else if (key.equals("javax.script.language_name")) {
			return "ECMAScript";
		}
		return null;
	}

	@Override
	@Unimplemented
	public String getMethodCallSyntax(final String obj, final String m, final String... args) {
		return null;
	}

	@Override
	@Unimplemented
	public String getOutputStatement(final String toDisplay) {
		return null;
	}

	@Override
	@Unimplemented
	public String getProgram(final String... statements) {
		return null;
	}

	@Override
	public ScriptEngine getScriptEngine() {
		return new RhinoJSE(this);
	}

	private static List<String> immutableList(String... elements) {
		return Lists.of(elements);
	}

	@Override
	public String toString() {
		return "RhinoJSE[adapter_version=1.0.1_1.7,hash=" + this.hashCode() + "]";
	}

	public static void main(String[] args) throws Exception {
		ArrayUtils.printLln(nScripting.factories());
	}
}
